import cn.edu.dgut.Entity.User;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/LocalLoginServlet")
public class LocalLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");
        EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
        String jpql = "select u from User u where u.user_number = :name";
        Query query = em.createQuery(jpql);
        query.setParameter("name",name);
        List resultList = query.getResultList();
        if(resultList.size()!=0){
            for (Object o : resultList) {
                User u = (User)o;
                if(u.getPassword().equals(request.getParameter("password"))){
                    Map<String, String> info = new HashMap<String, String>();
                    info.put("user_number", u.getUser_number());
                    info.put("name", u.getName());
                    info.put("faculty_title", u.getFaculty_title());
                    info.put("group", u.getType());
                    HttpSession session = request.getSession(true);
                    session.setAttribute("isLogin", info);
                    response.sendRedirect("/info.jsp");
                }else {
                    response.getWriter().println("密码不正确！！");
                }
            }
        }else {
            response.getWriter().println("用户不存在！！");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
